<template>
  <div class="art-full-height">
    <!-- 搜索区域 -->
    <CustomSearchBar
      v-model="searchForm"
      :form-items="searchFormList"
      @search="handleSearch"
      @reset="resetSearchParams"
    ></CustomSearchBar>
    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
        <template #left>
          <ElSpace wrap>
            <ElButton @click="showDialog('add')" v-ripple>新增管理员</ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>
      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
      </ArtTable>
    </ElCard>

    <!-- 表单 -->
    <customForm
      v-model:visible="visiable"
      :title="title"
      :width="400"
      :form-data="formData"
      @submit="getData"
    ></customForm>
  </div>
</template>
<script setup lang="ts">
  import {
    apiAddAdmin,
    apiDeleteAdmin,
    apiEditAdmin,
    apiGetAdmin,
    apiSearchAdmin
  } from '@/api/admin'
  import customForm from '@/components/custom/custom-form/customForm.vue'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import { useTable } from '@/composables/useTable'
  import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
  import { statusTagType } from '@/maps/index'
  import { isEmpty } from '@/utils'
  import {
    CustomInterfaceFormBody,
    CustomFormColumnsType
  } from '@/components/custom/custom-form/it'
  import { useUserStore } from '@/store/modules/user'
  import { SearchFormItem } from '@/components/core/forms/art-search-bar/index.vue'

  const userStore = useUserStore()
  const { getUserInfo: userInfo } = storeToRefs(userStore)

  // 搜索表单
  const searchForm = ref({
    username: undefined,
    addTime: undefined,
    status: undefined
  })

  //搜索表单项
  const searchFormList: SearchFormItem[] = [
    {
      label: '用户名',
      key: 'username',
      type: 'input',
      placeholder: '请输入用户名',
      clearable: true
    },
    {
      label: '状态',
      key: 'status',
      type: 'select',
      props: {
        placeholder: '请选择状态',
        options: [
          {
            label: '正常',
            value: '1'
          },
          {
            label: '禁用',
            value: '0'
          }
        ],
        clearable: true
      }
    },
    {
      label: '创建时间',
      key: 'addTime',
      type: 'datetime',
      props: {
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD',
        rangeSeparator: '至',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期'
      }
    }
  ]

  //搜索提交数据
  const searchData = ref({
    username: '',
    startTime: '',
    endTime: '',
    status: ''
  })

  //弹窗类型
  const dialogType = ref<Form.DialogType>('add')
  //弹窗展示状态
  const visiable = ref(false)
  //弹窗标题
  const title = ref('')
  //用户数据
  const editData = ref<Partial<any>>({})
  //表单数据
  const formData = ref<CustomInterfaceFormBody>({
    columns: [
      {
        type: CustomFormColumnsType.input,
        title: '用户名',
        name: 'username'
      },
      {
        type: CustomFormColumnsType.password,
        title: '密码',
        name: 'password'
      },
      {
        type: CustomFormColumnsType.radio,
        title: '状态',
        name: 'status',
        hidden: true,
        options: [
          {
            text: '正常',
            value: 1
          },
          {
            text: '禁用',
            value: 0
          }
        ],
        default: 1
      },
      {
        type: CustomFormColumnsType.input,
        title: '状态备注',
        hidden: true,
        name: 'statusRemark'
      }
    ],
    addFun: apiAddAdmin,
    getFun: apiGetAdmin,
    editFun: apiEditAdmin,
    rules: {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
    }
  })

  const getUserStatusConfig = (status: string): any => {
    return statusTagType[status]
  }

  //显示弹窗
  const showDialog = (type: Form.DialogType, row?: any): void => {
    dialogType.value = type
    editData.value = row || {}
    nextTick(() => {
      // dialogVisible.value = true
      title.value = '添加管理员'
      //设置隐藏字典
      formData.value.columns?.forEach((item) => {
        if (['status', 'statusRemark'].includes(item.name)) {
          item.hidden = true
        }
        if (['username'].includes(item.name)) {
          item.disabled = false
        }
      })
      // formData.value.title = '添加管理员'
      formData.value.isEdit = false
      formData.value.rules = {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
      visiable.value = true
    })
  }

  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: apiSearchAdmin,
      apiParams: {
        current: 1,
        size: 10,
        ...searchForm.value
      },
      columnsFactory: () => [
        { prop: 'id', width: 60, label: 'id', align: 'center' }, // 序号
        {
          prop: 'username',
          label: '用户名'
        },
        {
          prop: 'status',
          label: '状态',
          width: 90,
          align: 'center',
          formatter: (row: any) => {
            const statusConfig = getUserStatusConfig(row.status)
            return h(ElTag, { type: statusConfig.type }, () => statusConfig.text)
          }
        },
        {
          prop: 'statusRemark',
          label: '状态描述'
        },
        {
          prop: 'addTime',
          label: '创建日期',
          align: 'center',
          width: 180
        },
        {
          prop: 'operation',
          label: '操作',
          width: 120,
          fixed: 'right', // 固定列
          align: 'center',
          formatter: (row: any) =>
            h('div', [
              h(ArtButtonTable, {
                type: 'edit',
                title: '编辑',
                onClick: () => editRecord(row)
              }),
              h(ArtButtonTable, {
                type: 'delete',
                title: '删除',
                disabled: userInfo.value.id == row?.id,
                onClick: () => deleteRecord(row)
              })
            ])
        }
      ]
    }
  })

  //搜索
  const handleSearch = (params: any) => {
    searchData.value.username = params.username
    searchData.value.status = params.status
    searchData.value.startTime = ''
    searchData.value.endTime = ''
    if (!isEmpty(params.addTime)) {
      searchData.value.startTime = params.addTime[0] + ' 00:00:00'
      searchData.value.endTime = params.addTime[1] + ' 23:59:59'
    }
    // 搜索参数赋值
    Object.assign(searchParams, searchData.value)
    getData()
  }

  //编辑
  const editRecord = (row: any) => {
    title.value = '编辑管理员'
    //设置隐藏字典
    formData.value.columns?.forEach((item) => {
      if (['status', 'statusRemark'].includes(item.name)) {
        item.hidden = false
      }
      if (['username'].includes(item.name)) {
        item.disabled = true
      }
    })
    formData.value.isEdit = true
    formData.value.record = row
    formData.value.rules = {}
    visiable.value = true
  }

  //删除记录
  const deleteRecord = (row: any) => {
    ElMessageBox.confirm('确定要删除吗？<p>删除后无法恢复，请谨慎操作！</p>', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true
    }).then(() => {
      // console.log('删除')
      apiDeleteAdmin({
        id: row.id
      }).then((res) => {
        if (res) {
          ElMessage.success('删除成功')
          getData()
        } else {
          ElMessage.success('删除失败')
        }
      })
    })
  }
</script>
